<?php

class Filesystem extends BDS {

    protected static $tablename = "fs__files";

    static function changeMode($path, $mode) {
        $ok = false;
        if (file_exists($path) || is_dir($path)) {
            $ok = chmod($path, $mode);
        }
        return $ok;
    }

    static function GetFile($id) {
        $ok = false;
        BDS::Init();
        $result = Filesystem::Get($id);
        $file = $result;
        $file['uri'] = pathToUri($file['path']);
        $file['info'] = array();
        if (preg_match("#^image#", $file['type'])) {
            $info = getimagesize($file['path']);
            $file['info'] = array(
                'width' => $info[0],
                'height' => $info[1],
                'imagetype_const' => $info[2],
                'html_params' => $info[3],
                'mime_type' => $info['mime'],
            );
        }
        return $file;
    }

    static function Upload($data) {
        $ok = false;
        BDS::Init();
        $dest = ROOT_DIR . $GLOBALS['MAIN']->site->dir . "uploads/";
        foreach ($data as $field => $fileArray) {
            preg_match("#.([\w\d]+)$#", $fileArray['name'], $match);
            $ext = $match[1];
            $name = uniqid("file_") . ".$ext";
            $dest .= $name;
            $moved = move_uploaded_file($fileArray['tmp_name'], $dest);
            $id = Filesystem::Info('Auto_increment');
            if ($moved) {
                $data = array(
                    "id" => $id,
                    "title" => $fileArray['name'],
                    "name" => $fileArray['name'],
                    "path" => $dest,
                    "type" => $fileArray['type'],
                    "ext" => $ext,
                    "size" => $fileArray['size']
                );
                $ok = Filesystem::Create($data);
                $_FILES = array();
            }
        }
        return $ok->isTrue() ? $id : false;
    }

    static function Remove($id) {
        $ok = false;
        BDS::Init();
        $result = Filesystem::GetByID($id);
        $file = $result->fetch();
        if (file_exists($file['path'])) {
            $ok = Filesystem::removeFile($file['path']);
            $ok = Filesystem::Delete($id);
        }
        return $ok;
    }

    static function makeDir($path) {
        if (!is_dir($path)) {
            mkdir($path, DIR_MODE, true);
        }
    }

    static function moveDir($from, $to) {
        Filesystem::copyDir($from, $to);
        Filesystem::removeDir($from);
    }

    static function copyDir($from, $to) {
        $ok = false;
        if (is_dir($from)) {
            $tree = Filesystem::GetTree($from);
            foreach ($tree as $point) {
                $target = preg_replace("#$from#", $to, $point);
                if (preg_match("#\.[\w\d-]+$#", $target)) {
                    Filesystem::copyFile($point, $target);
                } else {
                    Filesystem::makeDir($target);
                }
            }
        }
        return $ok;
    }

    static function removeDir($path) {
        $ok = false;
        if (file_exists($path) && is_dir($path)) {            
            $dirHandle = opendir($path);
            while (false !== ($file = readdir($dirHandle))) {
                if ($file != '.' && $file != '..') {
                    $tmpPath = $path . '/' . $file;
                    chmod($tmpPath, 0777);
                    if (is_dir($tmpPath)) {
                        Filesystem::removeDir($tmpPath);
                    } else {
                        if (file_exists($tmpPath)) {
                            unlink($tmpPath);
                        }
                    }
                }
            }
            closedir($dirHandle);
            if (file_exists($path)) {
                rmdir($path);
            }
        } else {
            $ok = false;
        }
        return $ok;
    }

    static function createFile($path, $content = false) {
        $ok = false;
        if (!file_exists($path)) {
            $dir = dirname($path);
            if (!is_dir($dir)) {
                mkdir($dir, DIR_MODE, true);
            }
            $file = fopen($path, "w");
            if ($content) {
                fwrite($file, $content);
            }
            $ok = fclose($file);
        }
        return $ok;
    }

    static function moveFile($from, $to) {
        $ok = false;
        $ok = Filesystem::copyFile($from, $to);
        Filesystem::changeMode($path, 0777);
        $ok = unlink($from);
        return $ok;
    }

    static function copyFile($from, $to) {
        $ok = false;
        if (file_exists($from)) {
            $dest = dirname($to);
            if (!is_dir($dest)) {
                $ok = mkdir($dest, DIR_MODE, true);
            }
            $ok = copy($from, $to);
        }
        return $ok;
    }

    static function removeFile($path) {
        $ok = false;
        if (file_exists($path)) {
            Filesystem::changeMode($path, 0777);
            unlink($path);
        }
    }

    static function GetTree($path) {
        $tree = array();
        if (!is_dir($path)) {
            return $tree;
        }
        $dir = dir($path);
        $count = 0;
        while ($handle = $dir->read()) {
            if ($handle == "." || $handle == "..") {
                continue;
            }
            $count ++;
            $filename = "$path/$handle";
            if (is_dir($filename)) {
                $tree = array_merge($tree, Filesystem::GetTree("$path/$handle"));
            } else {
                $tree[] = $filename;
            }
        }
        if ($count == 0) {
            $tree[] = $path;
        }
        return $tree;
    }

    static function CreateBackup($path, $zipname = false) {
        $zip = new ZipArchive();
        $name = ROOT_DIR . "/frostcore/backup/" . "backup_". ($zipname ? $zipname."_" : false ) . time() . ".zip";
        $zip->open($name, ZipArchive::CREATE);
        $files = Filesystem::GetTree($path);
        foreach ($files as $file) {
            $filename = pathToUri($file);
            $filename = preg_replace("#^/#", "", $filename);
            if (preg_match("#frostcore/backup/#", $filename)) {
                continue;
            }
            if (preg_match("#\.[\w\d-]+$#", $filename)) {
                $zip->addFile($filename);
            } else {
                $zip->addEmptyDir(pathToUri($filename));
            }
        }
        
        $ok = $zip->close();
        return $name;
    }
}
